package com.fs.jzzn.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fs.base.utils.ApplicationUtils;
import com.fs.base.utils.DateUtils;
import com.fs.base.vo.JsonResponse;
import com.fs.base.vo.SysPath;
import com.fs.jzzn.pojo.Supplier;
import com.fs.jzzn.repository.SupplierRepository;

/**
 * 供应商controller
 * @author ACE
 *
 */
@Controller
@RequestMapping("/console/supplier/rewrite")
public class SupplierController {
	@Autowired SupplierRepository supplierRepository;
	
	@RequestMapping("/mySupplier")
	public String myUnit(HttpServletRequest request){
		Supplier unit = supplierRepository.findByCreaterId(ApplicationUtils.userId());
		if(unit==null){
			unit = new Supplier();
			unit.setCreaterId(ApplicationUtils.userId());
		}
		if(StringUtils.isBlank(unit.getUnitNo())){
			unit.setUnitNo("GYS" + DateUtils.curDate("yyMMddss"));
		}
		request.setAttribute("unit", JSON.toJSON(unit));
		return SysPath.BACK_PATH.concat("/supplier").concat("/mySupplier");
	}
	
	/**
	 * 供应商信息编辑
	 * @param unit
	 * @param request
	 * @return
	 */
	@RequestMapping("/modify")
	@ResponseBody
	public JsonResponse modify(Supplier unit,HttpServletRequest request){
		try {
			//新值
			Map<String, Object> newMap = ApplicationUtils.getRequestDatas();
			
			Supplier oldVo = null;
			if(StringUtils.isNotBlank(unit.getId())){
				oldVo = supplierRepository.findOne(unit.getId());
			}else{
				oldVo = unit;
			}
			String oldJson = JSON.toJSONString(oldVo);
			
			@SuppressWarnings("unchecked")
			Map<String, Object> oldMap = JSON.parseObject(oldJson, Map.class);
			oldMap.putAll(newMap);
			
			String newJson = JSON.toJSONString(oldMap) ;
			Supplier newVo = JSON.parseObject(newJson, Supplier.class);
			supplierRepository.save(newVo);
		} catch (Exception e) {
			JsonResponse.error("提交失败！");
			e.printStackTrace();
		}
		return JsonResponse.success();
	}
	
	@RequestMapping("/remark")
	@ResponseBody
	public JsonResponse remark(Supplier unit){
		try {
			Supplier _unit = supplierRepository.findOne(unit.getId());
			_unit.setStatus(unit.getStatus());
			supplierRepository.save(_unit);
		} catch (Exception e) {
			JsonResponse.error("备注失败！");
			e.printStackTrace();
		}
		return JsonResponse.success();
	}
}
